package com.uniview.web.api;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.ServletRequestUtils;

import com.uniview.base.BaseController;
import com.uniview.common.mapper.JsonMapper;
import com.uniview.entity.po.CCRelation;
import com.uniview.entity.po.Employees;
import com.uniview.entity.po.OrderCCRelation;
import com.uniview.entity.po.OrderLastRegion;
import com.uniview.entity.po.RegionManager;
import com.uniview.entity.po.ServiceOrderMedia;
import com.uniview.entity.po.ServiceOrderWarn;
import com.uniview.entity.po.ServiceOrders;
import com.uniview.entity.po.ServiceOrdersLogs;
import com.uniview.entity.vo.OrderAndRoleVO;
import com.uniview.entity.vo.OrderApprovalVO;
import com.uniview.entity.vo.OrderHandleVO;
import com.uniview.entity.vo.OrderMessage;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.ResultMessage;
import com.uniview.entity.vo.orderType.ExternalTest;
import com.uniview.entity.vo.orderType.OnlineProblems;
import com.uniview.entity.vo.orderType.ProjectDelivery;
import com.uniview.entity.vo.orderType.Rma;
import com.uniview.plugins.bpm.BpmService;
import com.uniview.plugins.epms.EPMSService;
import com.uniview.plugins.epms.ProjectSupport;
import com.uniview.plugins.epms.UserInfo;
import com.uniview.plugins.sms.ServiceDispatchSMS;
import com.uniview.plugins.workplus.WorkplusApiService;
import com.uniview.plugins.workplus.WorkplusMessagePushManager;
import com.uniview.service.CCRelationService;
import com.uniview.service.EmployeesService;
import com.uniview.service.RegionManagerService;
import com.uniview.service.ServiceOrderLastRegionService;
import com.uniview.service.ServiceOrderWarnService;
import com.uniview.service.ServiceOrdersLogsService;
import com.uniview.service.ServiceOrdersMediaService;
import com.uniview.service.ServiceOrdersService;
import com.uniview.service.orderType.OnlineProblemsService;
import com.uniview.service.orderType.ProjectDeliveryService;
import com.uniview.service.orderType.RmaService;
import com.uniview.util.DateUtil;
import com.uniview.web.contorller.ServiceOrdersController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ServiceOrderApi extends BaseController {
	Logger logger = Logger.getLogger(ServiceOrdersController.class);

	@Autowired
	private ServiceOrdersService srviceOrdersService;

	@Autowired
	private ServiceOrdersLogsService serviceOrdersLogsService;

	// @Autowired
	// private ExternalTestService externalTestService; // 对外测试数据接口

	@Autowired
	private OnlineProblemsService onlineProblemsService; // 在线问题数据接口

	@Autowired
	private ProjectDeliveryService projectDeliveryService; // 项目交付数据接口

	@Autowired
	private RmaService rmaService; // 备件维修数据接口

	@Autowired
	private WorkplusMessagePushManager pushManager;

	@Autowired
	private WorkplusApiService workplusApiService;

	@Autowired
	private RegionManagerService regionManagerService; // 片区管理接口

	@Autowired
	private EmployeesService employeesService;

	@Autowired
	private ServiceOrdersMediaService orderMediaService; // 工单媒体数据接口

	@Autowired
	private ServiceOrderLastRegionService lastRegionService;

	@Autowired
	private ServiceOrderWarnService orderWarnService; // 工单警告

	@Autowired
	private CCRelationService ccRelationSerivce; // 抄送人

	@Value("#{configProperties['uniview.deptLevel']}")
	private Integer officeLevel;

	@Autowired
	private EPMSService epmsService; // epms服务接口

	@Autowired
	private ServiceDispatchSMS dispatchSMS; // 短信接口

	@Value("#{configProperties['uniview.service_order.url']}")
	public String serviceOrderUrl;

	@Autowired
	private BpmService bpmservice; // bpm服务

	public String findExternalTestByworkNo(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "length", 10);
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			String queryString = ServletRequestUtils.getStringParameter(request, "queryString");

			// Pager<ExternalTest> pager =
			// externalTestService.findExternalTestByWorkNo(workNo, queryString, page,
			// limit);
			Pager<ExternalTest> pager = bpmservice.findExternalTestByWorkNo(workNo, queryString, page, limit);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("获取对外测试列表数据异常", e);
		}
		return getTableJsonString("[]", 0);
	}

	public String findOnlieProblemsByworkNo(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "limit", 10);
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			String queryString = ServletRequestUtils.getStringParameter(request, "queryString");
			Pager<OnlineProblems> pager = onlineProblemsService.findOnlineProblemsByWorkNo(workNo, queryString, page,
					limit);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("获取网上问题列表数据异常", e);
		}
		return getTableJsonString("[]", 0);
	}

	public String findProjectDeliveryByworkNo(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "limit", 10);
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			String queryString = ServletRequestUtils.getStringParameter(request, "queryString");

			if (StringUtils.isNotBlank(workNo)) {
				workNo = workNo.toUpperCase();
			}
			// Pager<ProjectDelivery> pager =
			// projectDeliveryService.findProjectDeliveryByWorkNo(workNo,queryString, page,
			// limit);
			UserInfo userInfo = epmsService.queryUserInfoById(workNo);
			Pager<ProjectDelivery> pager = epmsService.seniorSearchProject(userInfo, queryString, limit, page);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("获取项目交付列表数据异常", e);
		}
		return getTableJsonString("[]", 0);
	}

	public String findRmaByworkNo(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "length", 10);
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			String queryString = ServletRequestUtils.getStringParameter(request, "queryString");

			String operatorId = rmaService.findOperatorByUserId(workNo);
			if (StringUtils.isNotBlank(operatorId)) {
				Pager<Rma> pager = rmaService.findRmaOrdersByWorkNo(operatorId, queryString, page, limit);
				if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
					return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()), pager.getTotalRow());
				}
			}
			/*
			 * Pager<Rma> pager = rmaService.findRmaByWorkNo(workNo, queryString, page,
			 * limit); if (pager != null && pager.getPagerList() != null &&
			 * pager.getPagerList().size() > 0) { return
			 * getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()),
			 * pager.getTotalRow()); }
			 */
		} catch (Exception e) {
			logger.error("获取备件维修列表数据异常", e);
		}
		return getTableJsonString("[]", 0);
	}

	public String findServiceOrders(HttpServletRequest request) {
		try {
			int page = ServletRequestUtils.getIntParameter(request, "page", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "length", 10);
			String creator = ServletRequestUtils.getStringParameter(request, "creator");
			String handler = ServletRequestUtils.getStringParameter(request, "handler");
			String startDate = ServletRequestUtils.getStringParameter(request, "startDate");
			String endDate = ServletRequestUtils.getStringParameter(request, "endDate");
			String area = ServletRequestUtils.getStringParameter(request, "area");
			Integer status = ServletRequestUtils.getIntParameter(request, "status", -1);
			Pager<ServiceOrders> pager = srviceOrdersService.findAllOrders(creator, handler, startDate, endDate, area,
					status, limit, page);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				return getTableJsonString(JsonMapper.toJsonString(pager.getPagerList()), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("获取工单列表数据异常", e);
		}
		return getTableJsonString("[]", 0);
	}

	public ResultMessage addOrder(ServiceOrders order, String[] ccList) {

		if (StringUtils.isBlank(order.getCreatorNo())) {
			return this.getResult("创建人为空，请重新登录平台", false);
		}

		if (null != order.getId() && order.getId() > 0) {
			return updateOrder(order);
		}
		String msg = "";
		boolean result = false;
		try {
			if (!order.getOrderFrom().contains("网上问题")) {
				order.setOnlineProblemsName("");
				order.setOnlineOrderFromNo("");
			}
			order.setCreateTime(new Date());
			order.setModifyTime(new Date());
			order.setStatus("0");
			order.setInitDept(order.getHandlerDept());
			order.setInitUserName(order.getHandle());
			order.setInitWorkNo(order.getHandleNo());
			order.setManagerNo(order.getHandleNo());
			order.setOrderNo(NumberGenerater.getInstance(srviceOrdersService).geneterNextNumber());
			order.setSatisfaction(2); // 默认为未回复
			order.setDealStatus(0); // 默认未处理
			if (StringUtils.isNotBlank(order.getCreatorNo())) {
				Employees emp = employeesService.findEmployeesByWorkNo(order.getCreatorNo().toUpperCase());
				if (emp != null) {
					order.setCreator(emp.getEmpName());
					order.setCreatorNo(emp.getEmpCode());
					order.setCreatorDept(StringUtils.isNotBlank(emp.feachOffice(this.officeLevel))
							? emp.feachOffice(this.officeLevel)
							: emp.getOrgName());
					order.setCreatorJobTitle(emp.getPosition());
					// 调接口查头像和职位
					if (StringUtils.isBlank(order.getCreatorAvatar())) {
						JSONObject jsonObj = workplusApiService.getWorkplusEmployees(emp.getEmpCode());
						if (null != jsonObj) {
							Integer apiStatus = jsonObj.getInt("status");
							if (0 == apiStatus) {
								JSONArray resultJo = jsonObj.getJSONArray("result");
								if (null != resultJo && resultJo.size() > 0) {
									if (resultJo.getJSONObject(0).containsKey("avatar")) {
										order.setCreatorAvatar(resultJo.getJSONObject(0).getString("avatar"));
									}
								}
							}
						}
					}
				}
			}
			// 新增一个服务经理的创建工单规则，如果当前员工为服务经理，处理人也指定为自己 则跳过审批工单直接进入待处理的状态
			// RegionManager rm =
			// regionManagerService.findRegionManagerByWorkNo(order.getCreatorNo().toUpperCase());
			// if(rm !=null &&
			// rm.getWorkNo().toUpperCase().equals(order.getCreatorNo().toUpperCase())){
			// if(order.getCreatorNo().toUpperCase().equals(order.getHandleNo().toUpperCase())){
			// order.setStatus("1");
			// }
			// }

			ServiceOrdersLogs logs = new ServiceOrdersLogs();
			logs.setCreateTime(new Date());
			logs.setCreator(order.getCreator());
			logs.setCreatorNo(order.getCreatorNo());
			if (StringUtils.isNotBlank(order.getTaskDesc())) {
				logs.setHandler(order.getTaskDesc());
			} else {
				logs.setHandler("新增");
			}
			logs.setAssignName(order.getHandle());
			logs.setStauts(0);
			Integer orderId = srviceOrdersService.saveOrders(order, logs);
			if (orderId > 0) {
				msg = "创建成功";
				result = true;
				// 是否是服务经理
				RegionManager manager = regionManagerService.findRegionManagerByWorkNo(order.getCreatorNo());
				// 不是服务经理时修改默认办事处
				if (null == manager) {
					OrderLastRegion lastRegion = lastRegionService.findByCreatorNo(order.getCreatorNo());
					if (null != lastRegion) {
						// 如果与上次提交不相同，更新
						if (StringUtils.isNotBlank(lastRegion.getHandlerNo())
								&& !lastRegion.getHandlerNo().equals(order.getHandleNo())) {
							lastRegion.setHandler(order.getHandle());
							lastRegion.setHandlerNo(order.getHandleNo());
							lastRegion.setRegion(order.getHandlerDept());
							lastRegionService.updateRegion(lastRegion);
						}
					} else {
						lastRegion = new OrderLastRegion();
						lastRegion.setCreator(order.getCreatorNo());
						lastRegion.setHandler(order.getHandle());
						lastRegion.setHandlerNo(order.getHandleNo());
						lastRegion.setRegion(order.getHandlerDept());
						lastRegionService.saveRegion(lastRegion);
					}
				}

				// 抄送人处理
				if (null != ccList && ccList.length > 0) {
					ccRelationSerivce.removeCCByOwner(order.getCreatorNo());
					List<CCRelation> ccAddList = new ArrayList<CCRelation>();
					List<OrderCCRelation> orderCCAddList = new ArrayList<OrderCCRelation>();
					for (String empCode : ccList) {
						Employees ccEmp = employeesService.findEmployeesByWorkNo(empCode);
						if (null != ccEmp) {
							CCRelation cc = new CCRelation();
							cc.setEmpCode(ccEmp.getEmpCode());
							cc.setEmpName(ccEmp.getEmpName());
							cc.setOwner(order.getCreatorNo());
							ccAddList.add(cc);
							OrderCCRelation orderCC = new OrderCCRelation();
							orderCC.setCcUsername(ccEmp.getEmpCode());
							orderCC.setOrderId(orderId);
							orderCC.setCcName(ccEmp.getEmpName());
							orderCCAddList.add(orderCC);
						}
					}
					// 记录工单与抄送人的关联
					ccRelationSerivce.saveOrderCCRelation(orderCCAddList);
					// 记录用户的抄送人
					ccRelationSerivce.saveCCRelation(ccAddList);
				}

				// 推送创建工单消息
				try {
					String targetAlert = "服务派工[创建工单]通知";
					String handleType = "新建";
					OrderMessage orderMessage = this.getOrderMessage(handleType, this.serviceOrderUrl, order);
					if (StringUtils.isNotBlank(order.getHandleNo())) {
						List<String> userNames = new ArrayList<String>();
						userNames.add(order.getHandleNo());
						this.pushManager.pushMessage(targetAlert, "", targetAlert, orderMessage, userNames);
						if (null != ccList && ccList.length > 0) {
							Map<String, String> ccMap = new HashMap<String, String>();
							ccMap.put("app", "服务派工");
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							ccMap.put("date", sdf.format(order.getCreateTime()));
							ccMap.put("creator", order.getCreator());
							ccMap.put("content", "您收到一份待阅的服务工单消息，请查阅！");
							ccMap.put("url", this.serviceOrderUrl);
							this.pushManager.pushMessageByCC(targetAlert, "", targetAlert, ccMap,
									Arrays.asList(ccList));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				msg = "创建失败";
				result = false;
			}
		} catch (Exception e) {
			msg = "创建工单异常";
			result = false;
			logger.error("新增工单异常", e);
		}

		return getResult(msg, result);
	}

	/*
	 * private String createOrderNo(){ StringBuilder builder = new StringBuilder();
	 * builder.append("SD"); SimpleDateFormat format = new
	 * SimpleDateFormat("yyyyMMddHHmmss"); builder.append(format.format(new
	 * Date())); return builder.toString(); }
	 */

	public ResultMessage deleteOrder(int orderId, String creatorNo) {
		
		if (StringUtils.isBlank(creatorNo)) {
			return this.getResult("删除人为空，请重新登录平台", false);
		}
		
		String msg = "删除失败";
		boolean result = false;
		try {
			Employees emp = employeesService.findEmployeesByWorkNo(creatorNo.toUpperCase());
			if (emp != null) {
				// 记录删除操作日志
				ServiceOrdersLogs logs = new ServiceOrdersLogs();
				logs.setOrderId(orderId);
				logs.setCreateTime(new Date());
				logs.setHandler("删除工单");
				logs.setCreator(emp.getEmpName());
				logs.setCreatorNo(emp.getEmpCode());
				// 删除时工单状态改为-99
				logs.setStauts(-99);
				result = srviceOrdersService.updateOrderStatusByOrderId(orderId, logs);
				if (result) {
					msg = "删除成功！";
				}
			}
		} catch (Exception e) {
			msg = "删除工单异常！";
			logger.error(msg, e);
		}
		return getResult(msg, result);
	}

	public ResultMessage updateOrder(ServiceOrders order) {
		String msg = "修改失败";
		boolean result = false;
		try {
			ServiceOrders _order = srviceOrdersService.featchOrders(order.getId());
			if (_order != null) {
				order.setCreateTime(_order.getCreateTime());
			}
			order.setStatus("0");
			order.setManagerNo(order.getHandleNo());
			order.setModifyTime(new Date());
			ServiceOrdersLogs logs = new ServiceOrdersLogs();
			logs.setCreateTime(new Date());
			logs.setCreator(order.getCreator());
			logs.setCreatorNo(order.getCreatorNo());
			logs.setAssignName(order.getHandle());
			logs.setHandler("修改");
			logs.setStauts(0);
			result = srviceOrdersService.updateOrder(order, logs);
			// 是否为服务经理
			RegionManager manager = regionManagerService.findRegionManagerByWorkNo(order.getCreator());
			if (null == manager) {
				if (result) {
					OrderLastRegion lastRegion = lastRegionService.findByCreatorNo(order.getCreatorNo());
					if (null != lastRegion) {
						lastRegion.setHandler(order.getHandle());
						lastRegion.setHandlerNo(order.getHandleNo());
						lastRegion.setRegion(order.getHandlerDept());
						// 如果与上次提交不相同，更新
						if (!lastRegion.getHandlerNo().equals(order.getHandleNo())) {
							lastRegionService.updateRegion(lastRegion);
						}
					} else {
						lastRegion = new OrderLastRegion();
						lastRegion.setCreator(order.getCreatorNo());
						lastRegion.setHandler(order.getHandle());
						lastRegion.setHandlerNo(order.getHandleNo());
						lastRegion.setRegion(order.getHandlerDept());
						lastRegionService.saveRegion(lastRegion);
					}
					msg = "修改成功！";
				}
			}
		} catch (Exception e) {
			msg = "修改工单异常！";
			logger.error(msg, e);
		}
		return getResult(msg, result);
	}

	/**
	 * 审核工单
	 *
	 * @param request
	 * @return
	 */
	public ResultMessage applyOrder(HttpServletRequest request) {
		String msg = "审核失败";
		boolean result = false;
		try {
			int isUrgent = ServletRequestUtils.getIntParameter(request, "isUrgent", 0);
			int orderId = ServletRequestUtils.getIntParameter(request, "orderId", -1);
			String handler = ServletRequestUtils.getStringParameter(request, "handler");
			String handlerNo = ServletRequestUtils.getStringParameter(request, "handlerNo");
			String handlerDept = ServletRequestUtils.getStringParameter(request, "handlerDept");
			if (orderId > 0) {
				ServiceOrders order = srviceOrdersService.featchOrders(orderId);
				order.setModifyTime(new Date());
				if (order != null) {
					ServiceOrdersLogs logs = new ServiceOrdersLogs();
					logs.setCreator(handler);
					logs.setCreatorNo(handlerNo);
					if (isUrgent == 0) {
						// 审核通过
						if (StringUtils.isNotBlank(handler)) {
							order.setHandle(handler);
							order.setHandleNo(handlerNo);
							order.setHandlerDept(handlerDept);
						}

						order.setStatus("1"); // 审核通过
						logs.setCreateTime(new Date());
						logs.setHandler("审批工单");
						logs.setReMark("同意");
						logs.setStauts(1);
					} else {
						order.setStatus("3"); // 驳回
						order.setModifyTime(new Date());
						logs.setCreateTime(new Date());
						logs.setHandler("审批工单");
						logs.setReMark("不同意，被驳回");
						logs.setStauts(3);
					}

					result = srviceOrdersService.approveOrders(order, logs);

					if (result) {
						msg = "审核成功";
						// 发送推送消息
						String targetAlert = "";
						String handleType = "";
						if (order.getStatus().equals("1")) {
							targetAlert = "服务派工[工单审核]通知";
							handleType = "审核";
						} else {
							targetAlert = "服务派工[工单驳回]通知";
							handleType = "驳回";
						}
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						OrderMessage om = new OrderMessage();
						om.setCreateTime(dateFormat.format(order.getCreateTime()));
						om.setCustomerAddress(order.getCustomerAddress());
						om.setCustomerName(om.getCustomerName());
						om.setCustomerPhone(order.getCustomerPhone());
						om.setHandleType(handleType);
						om.setHandle(order.getHandle());
						om.setOrderFrom(order.getOrderFrom());
						om.setOrderFromName(order.getOrderFromName());
						om.setOrderNo(order.getOrderNo());
						om.setUrl(this.serviceOrderUrl);
						List<String> userNames = new ArrayList<String>();
						userNames.add(order.getHandleNo());
						pushManager.pushMessage(targetAlert, "", targetAlert, om, userNames);
					}
				}
			}

		} catch (Exception e) {
			msg = "审核工单异常";
			logger.error(msg, e);
		}

		return getResult(msg, result);
	}

	/**
	 * 催单
	 *
	 * @param request
	 * @return
	 */
	public ResultMessage urgeOrder(HttpServletRequest request) {
		String msg = "催单失败";
		boolean result = false;
		try {
			int orderId = ServletRequestUtils.getIntParameter(request, "orderId", -1);
			if (orderId > 0) {
				ServiceOrders order = srviceOrdersService.featchOrders(orderId);
				if (order != null) {
					// 获取工单处理人
					// String handler = order.getHandle();
					// 查找工单最近的催办日志
					ServiceOrdersLogs lastUrgeLog = this.serviceOrdersLogsService
							.findLastUrgeOrderLogByOrderId(orderId);
					if (null != lastUrgeLog) {
						Long urgeTime = lastUrgeLog.getCreateTime().getTime();
						Long currentTime = System.currentTimeMillis();
						Long distance = (currentTime - urgeTime) / 1000;
						if (distance < (30 * 60)) {
							return this.getResult("请勿频繁催单，请等待30分钟后再试", false);
						}
					}

					// 发送推送消息，提醒处理人尽快处理工单
					String targetAlert = "服务派工[催办工单]通知";
					String handleType = "催单";
					OrderMessage om = getOrderMessage(handleType, this.serviceOrderUrl, order);
					if (StringUtils.isNotBlank(order.getHandleNo())) {
						List<String> userNames = new ArrayList<String>();
						userNames.add(order.getHandleNo());
						pushManager.pushMessage(targetAlert, "", targetAlert, om, userNames);
					}
					// 记录工单操作日志
					ServiceOrdersLogs logs = new ServiceOrdersLogs();
					logs.setOrderId(orderId);
					logs.setCreateTime(new Date());
					logs.setHandler("催办工单");
					logs.setReMark("催单");
					logs.setStauts(0);
					Integer logsId = serviceOrdersLogsService.saveOrderLogs(logs);
					if (logsId > 0) {
						result = true;
						msg = "催单成功";
					}
				}
			}
			// 创建工单操作日志
		} catch (Exception e) {
			msg = "催办工单异常";
			logger.error(msg, e);
		}

		return getResult(msg, result);
	}

	/**
	 * 查询工单详情和用户角色
	 *
	 * @return
	 */
	public ResultMessage findOrdersByWorkNo(HttpServletRequest request) {
		try {
			// 分页参数
			int pageSize = ServletRequestUtils.getIntParameter(request, "pageSize", 0);
			int pageNo = ServletRequestUtils.getIntParameter(request, "pageNo", 0);
			// 当前用户工号
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			// 工单状态
			int status = ServletRequestUtils.getIntParameter(request, "status", 0);

			String query = ServletRequestUtils.getStringParameter(request, "query");

			// 判断用戶角色
			RegionManager rm = this.regionManagerService.findRegionManagerByWorkNo(workNo);
			Pager<ServiceOrders> pager = null;
			if (null != rm) {
				// 服务经理，获取所在办事情下属员工的工单，对应状态
				pager = srviceOrdersService.findOrdersByUserRole(2, workNo, query, status, pageSize, pageNo);
			} else {
				// 工程师或员工，自己管理的工单，对应状态
				pager = srviceOrdersService.findOrdersByUserRole(1, workNo, query, status, pageSize, pageNo);
			}

			// Pager<ServiceOrders> pager = srviceOrdersService.findOrdersByHandle(workNo,
			// status, pageSize, pageNo);

			if (pager != null) {
				if (pager.getPagerList() != null && pager.getPagerList().size() > 0) {
					return getResult("获取数据成功!", true, pager.getPagerList(), pager.getTotalRow());
				}
			}
		} catch (Exception e) {
			logger.error("获取工单信息异常", e);
		}

		return getResult("获取数据失败！", false);
	}

	/**
	 * 查询工单详情和用户角色
	 *
	 * @param orderId
	 * @param workNo
	 * @return
	 */
	public ResultMessage findOrderAndEmployeeRole(Integer orderId, String workNo) {
		try {
			if (StringUtils.isNotBlank(workNo) && orderId > 0) {
				OrderAndRoleVO vo = new OrderAndRoleVO();
				// 判断用户角色
				RegionManager rm = regionManagerService.findRegionManagerByWorkNo(workNo);
				if (null != rm) {
					vo.setUserRole(2);// 服务经理
				} else {
					vo.setUserRole(1); // 工程师
				}
				ServiceOrdersLogs ol = serviceOrdersLogsService.findApplyLogsByCreator(orderId);
				if (null != ol) {
					vo.setIsApprovaled(1);
				} else {
					vo.setIsApprovaled(0);
				}
				// 获取工单详情
				ServiceOrders order = srviceOrdersService.featchOrders(orderId);
				if (null != order) {
					vo.setOrder(order);
					return this.getResult("SUCCESS", true, vo);
				}
			} else {
				return this.getResult("用户和订单id不能为空", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.getResult("获取订单详情异常", false);
	}

	/**
	 * 根据关键字查询用户
	 *
	 * @param searchStr
	 * @param page
	 * @param limit
	 * @return
	 */
	public ResultMessage findEmployeesBySearch(String searchStr, String mangerNo, Integer page, Integer limit) {
		try {
			Pager<Employees> pager = employeesService.findEmployeesBySearch(searchStr, mangerNo, page, limit);
			if (pager != null && pager.getPagerList() != null && pager.getPagerList().size() > 0) {
				return this.getResult("success", true, pager.getPagerList(), pager.getTotalRow());
			}
		} catch (Exception e) {
			logger.error("获取员工信息异常", e);
		}

		return this.getResult("暂无数据", false);
	}

	/**
	 * 工单审批
	 *
	 * @param voParam
	 * @return
	 */
	public ResultMessage saveOrderApproval(OrderApprovalVO voParam) {
		try {
			if (null != voParam) {
				boolean isSuccess = false;
				// 判断用角色
				ServiceOrdersLogs logs = new ServiceOrdersLogs(voParam.getOrderId(), voParam.getHandler());
				// 审批意见
				if (StringUtils.isNotBlank(voParam.getApprove())) {
					logs.setHandler(voParam.getApprove());
				}
				ServiceOrders order = this.srviceOrdersService.featchOrders(voParam.getOrderId());
				String targetAlert = "";
				String handleType = "";
				if (2 == voParam.getUserRole()) { // 服务经理

					// if (StringUtils.isNotBlank(voParam.getContactName())) {
					order.setContactName(voParam.getContactName());
					order.setCustomerPhone(voParam.getCustomerPhone());
					order.setCustomerAddress(voParam.getCustomerAddress());
					// }

					// 处理人
					logs.setCreator(order.getHandle());
					logs.setCreatorNo(order.getHandleNo());

					// 指派人非空
					if (StringUtils.isNotBlank(voParam.getAssignUser())) {
						if (voParam.getAssignUser().equalsIgnoreCase(order.getCreatorNo())
								|| voParam.getAssignUser().equalsIgnoreCase(order.getManagerNo())) {
							// 如果指派人是创建人或者服务经理自己
							order.setStatus("1"); // 同意
							Employees emp = employeesService.findEmployeesByWorkNo(voParam.getAssignUser());
							order.setHandle(emp.getEmpName());
							order.setHandleNo(emp.getEmpCode());
							order.setHandlerDept(emp.feachOffice(this.officeLevel));
							logs.setStauts(Integer.parseInt(voParam.getStauts()));
							logs.setReMark("同意, 进入待处理");
						} else {
							order.setStatus("0");
							// 不一致，更新当前处理人
							Employees emp = employeesService.findEmployeesByWorkNo(voParam.getAssignUser());
							order.setHandle(emp.getEmpName());
							order.setHandleNo(emp.getEmpCode());
							order.setHandlerDept(emp.feachOffice(this.officeLevel));

							logs.setAssignName(voParam.getAssignName());
							logs.setStauts(Integer.parseInt(voParam.getStauts()));
							logs.setReMark("同意,流转到指派人审批");
						}
					} else {
						if ("1".equals(voParam.getStauts())) { // 同意
							order.setStatus("1"); // 同意
							logs.setStauts(Integer.parseInt(voParam.getStauts()));
							logs.setReMark("同意, 进入待处理");
						} else { // 拒绝
							// 服务经理拒绝，工单回到创建人，状态改为驳回
							if (order.getHandleNo().equalsIgnoreCase(order.getManagerNo())) {
								order.setStatus("3");
								order.setHandleNo(order.getCreatorNo());
								order.setHandle(order.getCreator());
								order.setHandlerDept(order.getCreatorDept());

								logs.setAssignName(order.getCreator());
								logs.setStauts(Integer.parseInt(voParam.getStauts()));
								logs.setReMark("服务经理不接受，被驳回，请修改工单");
							} else {
								// 工程师拒绝，工单回到服务经理，重新指派
								RegionManager rm = this.regionManagerService
										.findRegionManagerByWorkNo(order.getManagerNo());
								order.setStatus("0");
								order.setHandle(rm.getManager());
								order.setHandleNo(rm.getWorkNo());
								order.setHandlerDept(rm.getRegionName());

								logs.setAssignName(rm.getManager());
								logs.setStauts(Integer.parseInt(voParam.getStauts()));
								logs.setReMark("工程师不接受，被驳回，回到服务经理重新指派");
							}

						}
					}

					// 判断指派人和工单创建人是否一致
					/**
					 * if(StringUtils.isNotBlank(voParam.getAssignUser()) &&
					 * !voParam.getAssignUser().equalsIgnoreCase(order.getCreatorNo())) { //
					 * 不一致，更新当前处理人 Employees emp =
					 * employeesService.findEmployeesByWorkNo(voParam.getAssignUser());
					 * order.setHandle(emp.getEmpName()); order.setHandleNo(emp.getEmpCode());
					 * order.setHandlerDept(emp.feachOffice(this.officeLevel));
					 * 
					 * if ("1".equals(voParam.getStauts())) { // 同意 // 如果指派给非工单创建人，则工单状态还是待审批 //
					 * logs.setCreator(voParam.getAssignName()); ServiceOrdersLogs sol =
					 * serviceOrdersLogsService.findApplyLogsByCreator(order.getId()); if (null !=
					 * sol && !("3").equals(order.getStatus())) { order.setStatus("1");
					 * logs.setAssignName(voParam.getAssignName());
					 * logs.setStauts(Integer.parseInt(voParam.getStauts()));
					 * logs.setReMark("同意,流转到指派人处理工单"); } else {
					 * logs.setAssignName(voParam.getAssignName());
					 * logs.setStauts(Integer.parseInt(voParam.getStauts()));
					 * logs.setReMark("同意,流转到指派人审批"); } } else { // 拒绝 order.setStatus("3"); // 驳回
					 * // logs.setCreator(voParam.getAssignUser()); ServiceOrdersLogs ol =
					 * serviceOrdersLogsService.findApplyLogsByCreator(order.getId()); if(ol !=
					 * null){ // 工程师 Employees employee =
					 * this.employeesService.findEmployeesByWorkNo(ol.getCreatorNo()); //
					 * 获取当前处理人的服务经理 RegionManager rm =
					 * this.regionManagerService.findRegionManagerByWorkNo(employee.getEmpCode());
					 * // 处理人改为服务经理 if (null != employee && null != rm) {
					 * order.setHandle(rm.getManager()); order.setHandleNo(rm.getWorkNo());
					 * order.setHandlerDept(rm.getRegionName()); } } else {
					 * order.setHandle(order.getCreator()); order.setHandleNo(order.getCreatorNo());
					 * order.setHandlerDept(order.getCreatorDept()); }
					 * logs.setAssignName(order.getCreator());
					 * logs.setStauts(Integer.parseInt(voParam.getStauts())); logs.setReMark("驳回");
					 * } } else { // order.setHandle(order.getCreator()); //
					 * order.setHandleNo(order.getCreatorNo()); //
					 * order.setHandlerDept(order.getCreatorDept()); if
					 * ("1".equals(voParam.getStauts())) { order.setStatus("1"); // 同意
					 * logs.setStauts(Integer.parseInt(voParam.getStauts())); logs.setReMark("同意,
					 * 进入待处理"); } else { order.setStatus("3"); // 驳回
					 * logs.setCreator(order.getHandleNo()); ServiceOrdersLogs ol =
					 * serviceOrdersLogsService.findApplyLogsByCreator(order.getId()); if(ol !=
					 * null){ // 工程师 Employees employee =
					 * this.employeesService.findEmployeesByWorkNo(ol.getCreatorNo()); //
					 * 获取当前处理人的服务经理 RegionManager rm =
					 * this.regionManagerService.findRegionManagerByWorkNo(employee.getEmpCode());
					 * // 处理人改为服务经理 if (null != employee && null != rm) {
					 * order.setHandle(rm.getManager()); order.setHandleNo(rm.getWorkNo());
					 * order.setHandlerDept(rm.getRegionName()); } } else {
					 * order.setHandle(order.getCreator()); order.setHandleNo(order.getCreatorNo());
					 * order.setHandlerDept(order.getCreatorDept()); }
					 * logs.setAssignName(order.getCreator());
					 * logs.setStauts(Integer.parseInt(voParam.getStauts())); logs.setReMark("驳回");
					 * } }
					 */

					if ("1".equals(voParam.getStauts())) {
						targetAlert = "服务派工[工单审核]通知";
						handleType = "同意";
					} else {
						targetAlert = "服务派工[工单驳回]通知";
						handleType = "不同意";
					}
					order.setModifyTime(new Date());
					logs.setCreateTime(new Date());
					isSuccess = this.srviceOrdersService.approveOrders(order, logs);
					if (isSuccess) {
						try { // TODO 消息推送(给工程师推送)
							OrderMessage orderMessage = getOrderMessage(handleType, this.serviceOrderUrl, order);
							List<String> userNames = new ArrayList<String>();
							userNames.add(order.getHandleNo());
							this.pushManager.pushMessage(targetAlert, "", targetAlert, orderMessage, userNames);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else { // 工程师提交的审批结果
					logs.setCreator(order.getHandle());
					logs.setCreatorNo(order.getHandleNo());

					if ("1".equals(voParam.getStauts())) {// 接收
						// 更新工单信息
						order.setStatus("1");
						order.setModifyTime(new Date());
						// 新增工单日志
						// logs.setCreator(order.getHandleNo());
						logs.setStauts(Integer.parseInt(voParam.getStauts()));
						logs.setReMark("接受");

						targetAlert = "服务派工[工单接受]通知";
						handleType = "接受";
					} else {// 拒绝
						// 更新工单信息
						order.setStatus("0"); // 驳回
						RegionManager rm = this.regionManagerService.findRegionManagerByWorkNo(order.getManagerNo());
						if (null != rm) {
							order.setHandle(rm.getManager());
							order.setHandleNo(rm.getWorkNo());
							order.setHandlerDept(rm.getRegionName());
						}
						/**
						 * ServiceOrdersLogs ol =
						 * serviceOrdersLogsService.findApplyLogsByCreator(order.getId()); if(ol
						 * !=null){ // 工程师 Employees employee =
						 * this.employeesService.findEmployeesByWorkNo(ol.getCreatorNo()); //
						 * 获取当前处理人的服务经理 RegionManager rm =
						 * this.regionManagerService.findRegionManagerByWorkNo(employee.getEmpCode());
						 * // 处理人改为服务经理 if (null != employee && null != rm) {
						 * order.setHandle(rm.getManager()); order.setHandleNo(rm.getWorkNo());
						 * order.setHandlerDept(rm.getRegionName()); } }
						 */

						order.setModifyTime(new Date());
						// 新增工单日志
						// logs.setCreator(order.getHandleNo());
						logs.setAssignName(order.getHandle());
						logs.setStauts(Integer.parseInt(voParam.getStauts()));
						logs.setReMark("拒绝");
						targetAlert = "服务派工[工单拒绝]通知";
						handleType = "拒绝";
					}
					order.setModifyTime(new Date());
					logs.setCreateTime(new Date());
					isSuccess = srviceOrdersService.approveOrders(order, logs);
					if (isSuccess) {
						try {
							// TODO 消息推送(给服务经理推送)
							OrderMessage orderMessage = getOrderMessage(handleType, "", order);
							List<String> userNames = new ArrayList<String>();
							userNames.add(order.getHandleNo());
							this.pushManager.pushMessage(targetAlert, "", targetAlert, orderMessage, userNames);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				if (isSuccess) {
					return this.getResult("工单处理成功", true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.getResult("提交工单审批异常", false);
	}

	/**
	 * 工单签到
	 *
	 * @param workNo
	 * @param orderId
	 * @return
	 */
	public ResultMessage doOrderSign(String workNo, Integer orderId, String address, Integer isWarning) {
		try {
			ServiceOrders order = this.srviceOrdersService.featchOrders(orderId);
			Employees emp = this.employeesService.findEmployeesByWorkNo(workNo);
			if (null != emp) {
				// 更新工时开始时间
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				String startTimeStr = sdf.format(new Date());
				order.setStartTime(sdf.parse(startTimeStr)); // 记录到分钟，不算秒
				order.setStatus("2");
				order.setIsWarning(isWarning);
				order.setModifyTime(new Date());
				// 添加日志
				ServiceOrdersLogs log = new ServiceOrdersLogs();
				log.setCreateTime(new Date());
				log.setCreator(emp.getEmpName());
				log.setHandler("签到: " + address);
				log.setId(orderId);
				log.setCreator(order.getHandle());
				log.setCreatorNo(order.getHandleNo());

				// 保存警告信息
				if (1 == isWarning) {
					ServiceOrderWarn warn = new ServiceOrderWarn();
					warn.setHandlerNo(emp.getEmpCode());
					warn.setHandler(emp.getEmpName());
					warn.setOrderId(orderId);
					warn.setWarnContent("签到地址不在客户地址范围内");
					warn.setWarnTime(new Date());
					this.orderWarnService.save(warn);
				}

				boolean isSuccess = this.srviceOrdersService.handleOrder(order, log);
				if (isSuccess) {
					return this.getResult("SUCCESS", true);
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return this.getResult("工单签到异常", false);
	}

	public ResultMessage findOfficeByQuery(String queryString, int page, int limit) {
		try {
			Pager<RegionManager> pager = regionManagerService.findRegionByPage(queryString, limit, page);
			if (pager != null && pager.getPagerList() != null) {
				return getResult("获取办事处成功", true, pager.getPagerList(), pager.getTotalRow());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this.getResult("获取办事处失败!", false);
	}

	public ResultMessage checkIsManager(HttpServletRequest request) {
		String msg = "操作失败";
		boolean result = false;
		try {
			String workNo = ServletRequestUtils.getStringParameter(request, "workNo");
			RegionManager rm = regionManagerService.findRegionManagerByWorkNo(workNo.toUpperCase());
			if (rm != null) {
				result = true;
				msg = "操作成功";
			} else {
				// 获取上次提交办事处
				OrderLastRegion region = lastRegionService.findByCreatorNo(workNo);
				if (null != region) {
					return getResult(msg, result, region);
				}
				msg = "没有默认办事处";
			}
		} catch (Exception e) {
			msg = "数据读取异常";
			logger.error("数据读取异常", e);
		}

		return getResult(msg, result);
	}

	public ResultMessage findEmployees(String workNo) {
		try {
			Employees emp = employeesService.findEmployeesByWorkNo(workNo.toUpperCase());
			if (emp != null) {
				return getResult("成功", true, emp);
			}
		} catch (Exception e) {
			logger.error("数据读取异常", e);
		}

		return getResult("数据读取失败", false);
	}

	public ResultMessage saveOrderHandle(OrderHandleVO vo, String[] medias, int isWarnning, String address) {
		try {
			ServiceOrders order = this.srviceOrdersService.featchOrders(vo.getOrderId());
			Employees emp = employeesService.findEmployeesByWorkNo(vo.getWorkNo());
			if (null != emp && null != order) {
				// 更新工单信息
				order.setStatus("4");
				order.setContactName(vo.getContactName());
				order.setCustomerPhone(vo.getContactPhone());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				order.setEndTime(sdf.parse(vo.getEndTime()));
				order.setHandleDesc(vo.getHandlerDesc());
				order.setModifyTime(new Date());
				// 计算工单的处理工时
				float hours = DateUtil.getHoursBetwee2Date(order.getStartTime(), order.getEndTime());
				logger.debug("工单开始时间========" + order.getStartTime() + "---" + order.getEndTime());
				logger.debug("========工单处理工时：" + hours);
				order.setWorkHours(hours);
				// 工单日志
				ServiceOrdersLogs log = new ServiceOrdersLogs();
				log.setCreateTime(new Date());
				log.setCreator(emp.getEmpName());
				log.setCreatorNo(emp.getEmpCode());
				log.setReMark("签退: " + address);
				log.setHandler(vo.getHandlerDesc());
				log.setOrderId(vo.getOrderId());

				// 保存警告信息
				if (1 == isWarnning) {
					ServiceOrderWarn warn = new ServiceOrderWarn();
					warn.setHandlerNo(emp.getEmpCode());
					warn.setHandler(emp.getEmpName());
					warn.setOrderId(vo.getOrderId());
					warn.setWarnContent("签退地址不在客户地址范围内");
					warn.setWarnTime(new Date());
					this.orderWarnService.save(warn);
				}

				boolean isSuccess = this.srviceOrdersService.handleOrder(order, log);

				// 附件上传
				if (isSuccess && null != medias && medias.length > 0) {
					for (int i = 0; i < medias.length; i++) {
						ServiceOrderMedia orderMedia = new ServiceOrderMedia();
						orderMedia.setMediaId(medias[i]);
						orderMedia.setOrderId(vo.getOrderId());
						orderMediaService.save(orderMedia);
					}
				}
				if (isSuccess) {
					try {
						// TODO 消息推送(给服务经理推送)
						String targetAlert = "服务派工[工单处理]通知";
						String handleType = "处理结束";
						Employees employee = this.employeesService.findEmployeesByWorkNo(order.getHandleNo());
						if (null != employee) {
							String office = employee.feachOffice(officeLevel);
							// 获取当前处理人的服务经理
							RegionManager rm = this.regionManagerService.findRegionManagerByRegionName(office);
							OrderMessage orderMessage = getOrderMessage(handleType, this.serviceOrderUrl, order);
							List<String> userNames = new ArrayList<String>();
							if (null != rm && StringUtils.isNotBlank(rm.getWorkNo())) {
								userNames.add(rm.getWorkNo());
								this.pushManager.pushMessage(targetAlert, "", targetAlert, orderMessage, userNames);
							}
						}

						// 发短信
						if (!order.getOrderFrom().contains("对外测试")) { // 排除对外测试工单
							// 判断是否衍生工单，如果是衍生工单，如果父工单的开始时间超过3天，则发送短信，否则不发
							if (order.getParentId() > 0) {
								ServiceOrders parentOrder = this.srviceOrdersService.featchOrders(order.getParentId());
								Date parentStart = parentOrder.getStartTime();
								int between = DateUtil.betweenDayOfNow(parentStart);
								if (between > 3) {
									dispatchSMS.sendSms(order.getContactName(), order.getId(),
											order.getCustomerPhone());
								}
							} else {
								dispatchSMS.sendSms(order.getContactName(), order.getId(), order.getCustomerPhone());
							}
						}

						// 将项目交付的数据同步的EPMS
						if (StringUtils.isNotBlank(order.getOrderFrom()) && order.getOrderFrom().contains("项目交付")) {
							logger.info("========工单处理已提交，同步到epms");
							ProjectSupport support = new ProjectSupport();
							// 查项目id
							Integer projectId = this.projectDeliveryService
									.findProjectIdByProjectNo(order.getOrderFromNo());
							support.setProjectId(projectId);
							support.setStartDt(order.getStartTime());
							support.setEndDt(order.getEndTime());
							// 计算工时
							float workhours = order.getWorkHours();
							float days = workhours / 8.00f;
							// 保留2位小数
							days = (float) (Math.round(days * 100)) / 100;
							if (days > 1.5f) {
								days = 1.5f;
							}
							// support.setDays(order.getWorkHours());
							support.setDays(days);
							support.setSupportPrice(vo.getUserRole() == 2 ? 1500 : 1200);
							support.setSupportContent(vo.getHandlerDesc());
							support.setSupportType(vo.getSupportType());
							Integer userId = epmsService.findUserInfoByAccount(emp.getEmpCode());
							support.setSupportUser(userId);
							epmsService.saveProjectSupport(support);
						}
					} catch (Exception e) {
						logger.error(e.getMessage());
					}
					return this.getResult("SUCCESS", true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.getResult("提交工单处理信息异常", false);
	}

	/**
	 * 消息推送封装
	 *
	 * @param handleType
	 * @param url
	 * @param order
	 * @return
	 * @throws Exception
	 */
	public OrderMessage getOrderMessage(String handleType, String url, ServiceOrders order) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		OrderMessage orderMessage = new OrderMessage();
		orderMessage.setCreateTime(dateFormat.format(order.getCreateTime()));
		orderMessage.setCustomerAddress(order.getCustomerAddress());
		orderMessage.setCustomerName(order.getCustomerName());
		orderMessage.setCustomerPhone(order.getCustomerPhone());
		orderMessage.setHandle(order.getHandle());
		orderMessage.setHandleType(handleType);
		orderMessage.setOrderFrom(order.getOrderFrom());
		orderMessage.setOrderFromName(order.getOrderFromName());
		orderMessage.setOrderNo(order.getOrderNo());
		orderMessage.setUrl(url);
		return orderMessage;
	}

	public ResultMessage findOrderById(int orderId) {
		try {
			ServiceOrders orders = srviceOrdersService.featchOrders(orderId);
			if (orders != null) {
				return getResult("工单数据读取成功", true, orders);
			}
		} catch (Exception e) {
			logger.error("工单数据读取异常", e);
		}

		return getResult("工单数据读取失败", false);
	}

	public ResultMessage findOrderDetailAndLogsByOrderId(int orderId) {
		try {
			ServiceOrders orders = srviceOrdersService.featchOrders(orderId);
			if (orders != null) {
				// 查警告信息
				List<ServiceOrderWarn> warns = this.orderWarnService.findWarnsByOrderId(orderId);
				orders.setWarns(warns);
				// 查媒体信息
				List<ServiceOrderMedia> medias = this.orderMediaService.findMediasByOrderId(orderId);
				orders.setMedias(medias);				
				// 查抄送对象
				List<OrderCCRelation> orderCCRelations = ccRelationSerivce.findOrderCCRelationByOrderId(orderId);
				orders.setOrderCCRelations(orderCCRelations);
				
				// 查日志信息
				List<ServiceOrdersLogs> logs = serviceOrdersLogsService.findLogByOrderId(orderId);
				return getResult("工单数据读取成功", true, logs, orders);
			}
		} catch (Exception e) {
			logger.error("工单数据读取异常", e);
		}

		return getResult("工单数据读取失败", false);
	}

	/**
	 * 获取用户的抄送人
	 * 
	 * @param username
	 * @return
	 */
	public ResultMessage getCCByUser(String username) {
		try {
			List<CCRelation> list = this.ccRelationSerivce.findCCByOwner(username);
			if (null != list && !list.isEmpty()) {
				return this.getResult("success", true, list);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.getResult("获取用户抄送人列表失败", false);
	}

	/**
	 * 补全缺省状态
	 *
	 * @param map
	 * @return
	 */
	public Map<String, Object> fillStatus(Map<String, Object> map) {
		// 工单状态 0 待审批 1 待处理 2 处理中 3 驳回 4 结束 5 关闭 6 草稿
		if (map.get("count0") == null) {
			map.put("count0", 0);
		}
		if (map.get("count1") == null) {
			map.put("count1", 0);
		}
		if (map.get("count2") == null) {
			map.put("count2", 0);
		}
		if (map.get("count3") == null) {
			map.put("count3", 0);
		}
		if (map.get("count4") == null) {
			map.put("count4", 0);
		}
		if (map.get("count5") == null) {
			map.put("count5", 0);
		}
		if (map.get("count6") == null) {
			map.put("count6", 0);
		}
		return map;
	}
}
